package com.szh.publisher.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware {

    @Resource
    private RabbitTemplate rabbitTemplate;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback(){

            @Override
            public void confirm(CorrelationData data, boolean ack, String cause) {
                log.error("ConfirmCallback -->ack:{},cause:{},",ack,cause);
                
            }
        });
        // ReturnCallback 设置 发送端： exchange--queue 的确认回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 只要消息没有投递给指定的队列，就会触发这个失败回调
             * @param message 投递失败的消息的详细信息
             * @param replyCode 回复的状态码
             * @param replyText 回复的文本内容
             * @param exchange 当时这个消息是发给那个交换机
             * @param routingKey 当时这个消息的路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

                // 延时队列，跳过
                if (message.getMessageProperties().getReceivedDelay() == null ||message.getMessageProperties().getReceivedDelay() >0){
                    return;
                }
                // 记录日志
                log.error("消息发送到队列失败，响应码：{}, 失败原因：{}, 交换机: {}, 路由key：{}, 消息: {}",
                        replyCode, replyText, exchange, routingKey, message.toString());
                // 如果有需要的话，重发消息
            };

        });

    }
}
